package service

import (
	"context"
	"fmt"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/dao"
	"time"
)

// AutoDetectAndFix 自动检测和修复异常
func (s *Server) AutoDetectAndFix(ctx context.Context, req *__.AutoDetectAndFixReq) (*__.AutoDetectAndFixResp, error) {
	// 检测异常交易
	err := dao.DetectAbnormalTransactions()
	if err != nil {
		return nil, err
	}

	// 获取待处理的异常交易
	abnormalTransactions, _, err := dao.GetAbnormalTransactions(1, 1, 1000) // 获取所有待处理的异常
	if err != nil {
		return nil, err
	}

	detectedCount := len(abnormalTransactions)
	fixedCount := 0
	manualCount := 0

	// 按异常类型统计
	abnormalTypeCount := make(map[uint8]int)

	for _, transaction := range abnormalTransactions {
		abnormalTypeCount[transaction.AbnormalType]++

		// 尝试自动修复
		canAutoFix, fixResult := dao.TryAutoFix(transaction)
		if canAutoFix {
			// 自动修复
			err = dao.ProcessAbnormalTransaction(transaction.ID, fixResult, 0) // 0表示系统自动处理
			if err == nil {
				fixedCount++
			}
		} else {
			manualCount++
		}
	}

	// 构建异常摘要
	var abnormalDetails []*__.AbnormalSummary
	abnormalTypeNames := map[uint8]string{
		1: "重复扣款",
		2: "金额不符",
		3: "时间异常",
		4: "状态异常",
	}

	for abnormalType, count := range abnormalTypeCount {
		abnormalDetails = append(abnormalDetails, &__.AbnormalSummary{
			AbnormalType: abnormalTypeNames[abnormalType],
			Count:        int32(count),
			Description:  dao.GetAbnormalDescription(abnormalType),
		})
	}

	return &__.AutoDetectAndFixResp{
		DetectedCount:   int32(detectedCount),
		FixedCount:      int32(fixedCount),
		ManualCount:     int32(manualCount),
		AbnormalDetails: abnormalDetails,
	}, nil
}

// ManualProcess 人工处理异常
func (s *Server) ManualProcess(ctx context.Context, req *__.ManualProcessReq) (*__.ManualProcessResp, error) {
	// 根据处理动作执行相应操作
	var result string
	var err error

	switch req.Action {
	case "refund":
		result, err = dao.ProcessRefund(req)
	case "adjust":
		result, err = dao.ProcessAdjustment(req)
	case "ignore":
		result, err = dao.ProcessIgnore(req)
	default:
		return nil, fmt.Errorf("不支持的处理动作: %s", req.Action)
	}

	if err != nil {
		return &__.ManualProcessResp{
			Success: false,
			Message: err.Error(),
		}, nil
	}

	// 更新异常交易状态
	err = dao.ProcessAbnormalTransaction(req.AbnormalId, result, req.ProcessedBy)
	if err != nil {
		return &__.ManualProcessResp{
			Success: false,
			Message: err.Error(),
		}, nil
	}

	return &__.ManualProcessResp{
		Success:     true,
		Message:     "处理成功",
		ProcessedAt: time.Now().Format("2006-01-02 15:04:05"),
	}, nil
}

// GetExceptionSummary 获取异常摘要
func (s *Server) GetExceptionSummary(ctx context.Context, req *__.GetExceptionSummaryReq) (*__.GetExceptionSummaryResp, error) {
	// 获取异常交易统计
	abnormalTransactions, _, err := dao.GetAbnormalTransactions(0, 1, 1000)
	if err != nil {
		return nil, err
	}

	// 获取争议记录统计
	disputes, _, err := dao.GetDisputeRecords(0, 1, 1000)
	if err != nil {
		return nil, err
	}

	// 统计异常类型
	abnormalTypeStats := make(map[uint8]__.AbnormalTypeSummary)
	abnormalTypeNames := map[uint8]string{
		1: "重复扣款",
		2: "金额不符",
		3: "时间异常",
		4: "状态异常",
	}

	for _, transaction := range abnormalTransactions {
		stats := abnormalTypeStats[transaction.AbnormalType]
		stats.Type = abnormalTypeNames[transaction.AbnormalType]
		stats.Count++
		if transaction.Status == 2 { // 已处理
			stats.Resolved++
		} else {
			stats.Pending++
		}
		abnormalTypeStats[transaction.AbnormalType] = stats
	}

	// 统计争议类型
	disputeTypeStats := make(map[uint8]__.DisputeTypeSummary)
	disputeTypeNames := map[uint8]string{
		1: "金额不符",
		2: "重复扣费",
		3: "服务未提供",
		4: "其他",
	}

	for _, dispute := range disputes {
		stats := disputeTypeStats[dispute.DisputeType]
		stats.Type = disputeTypeNames[dispute.DisputeType]
		stats.Count++
		if dispute.Status == 3 { // 已解决
			stats.Resolved++
		} else {
			stats.Pending++
		}
		disputeTypeStats[dispute.DisputeType] = stats
	}

	// 构建响应
	var abnormalByType []*__.AbnormalTypeSummary
	for _, stats := range abnormalTypeStats {
		abnormalByType = append(abnormalByType, &__.AbnormalTypeSummary{
			Type:     stats.Type,
			Count:    stats.Count,
			Pending:  stats.Pending,
			Resolved: stats.Resolved,
		})
	}

	var disputeByType []*__.DisputeTypeSummary
	for _, stats := range disputeTypeStats {
		disputeByType = append(disputeByType, &__.DisputeTypeSummary{
			Type:     stats.Type,
			Count:    stats.Count,
			Pending:  stats.Pending,
			Resolved: stats.Resolved,
		})
	}

	return &__.GetExceptionSummaryResp{
		TotalAbnormal:  int32(len(abnormalTransactions)),
		TotalDisputes:  int32(len(disputes)),
		ResolvedCount:  int32(dao.CountResolved(abnormalTransactions, disputes)),
		PendingCount:   int32(dao.CountPending(abnormalTransactions, disputes)),
		AbnormalByType: abnormalByType,
		DisputeByType:  disputeByType,
	}, nil
}
